/**
 * 
 */
package com.mbengue.corp.apr.ra.beans;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;

import com.mbengue.corp.apr.ra.core.Article;
import com.mbengue.corp.apr.ra.core.ArticleMembre;
import com.mbengue.corp.apr.ra.core.ArticleMembreId;
import com.mbengue.corp.apr.ra.core.Image;
import com.mbengue.corp.apr.ra.core.ImageArticle;
import com.mbengue.corp.apr.ra.core.ImageArticleId;
import com.mbengue.corp.apr.ra.core.Membre;
import com.mbengue.corp.apr.ra.dao.ArticleDao;
import com.mbengue.corp.apr.ra.dao.DAOFactory;
import com.mbengue.corp.apr.ra.dao.impl.ArticleMembreDaoImpl;
import com.mbengue.corp.apr.ra.dao.impl.ImageArticleDaoImpl;
import com.mbengue.corp.apr.ra.dao.impl.ImageDaoImpl;

/**
 * @author MMB11447
 *
 */
@ManagedBean(name = "articleBean")
@SessionScoped
public class ArticleBean implements Serializable {
  private static final long serialVersionUID = 1L;
  private Article article;
  private ArticleDao articleDao;
  private Image image;
  private Date debut;
  private Date fin;
  private List<Article> results;
  private HtmlOutputText text;
  private String titre;
  private String type;
  private String retour;

  public ArticleBean() {
    type = "date";
    article = new Article();
    articleDao = DAOFactory.getArticleDao();
  }

  public String enregistrer() {
    String redirect = "#";
    if (article.getTitre().isEmpty() || article.getResume().isEmpty() || article.getContenu().isEmpty()) {
      FacesContext.getCurrentInstance().addMessage(null,
          new FacesMessage(FacesMessage.SEVERITY_ERROR, "Tous les champs sont obligatoires", ""));
      return redirect;
    }
    //
    if (articleDao.trouverArticle(article.getTitre()) != null) {
      FacesContext.getCurrentInstance().addMessage(null,
          new FacesMessage(FacesMessage.SEVERITY_ERROR, "Un article avec ce titre existe déjà !", ""));
      return redirect;
    }
    //
    try {
      Membre connectedUser = ((LoggingBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
          .get("logging")).getConnectedUser();
      article.setDateDeCreation(new Date());
      article.setType("Article");
      articleDao.ajouterArticle(article);
      ArticleMembreId id = new ArticleMembreId(connectedUser.getEmail(), article.getTitre());
      ArticleMembre am = new ArticleMembre(id, article, connectedUser);
      new ArticleMembreDaoImpl().ajouter(am);
      if (image != null) {
        new ImageDaoImpl().ajouterImage(image);
        ImageArticleId idIA = new ImageArticleId(article.getTitre(), image.getNom());
        ImageArticle ia = new ImageArticle(idIA, article, image);
        new ImageArticleDaoImpl().ajouter(ia);
      }
      FacesContext.getCurrentInstance().addMessage(null,
          new FacesMessage(FacesMessage.SEVERITY_INFO, "Article enregistré ", "avec succés!"));
      redirect = "/pages/articles.xhtml?faces-redirect=true";
    } catch (Exception e) {
      e.printStackTrace();
      FacesContext.getCurrentInstance().addMessage(null,
          new FacesMessage(FacesMessage.SEVERITY_ERROR, "Un erreur est survenu ", "Echec de l'opération!"));
    } finally {
      article = new Article();
      image = null;
    }
    return redirect;
  }

  public void rechercherArticlesParDate() {
    results = new ArrayList<Article>();
    results = articleDao.findArticlesParDates(debut, fin, "Article");
  }

  public void rechercherArticlesParTitre() {
    results = new ArrayList<Article>();
    results = articleDao.findArticlesParTitre(titre, "Article");
  }

  public List<Article> getResults() {
    return results;
  }

  public Date getDebut() {
    return debut;
  }

  public void setDebut(Date aDebut) {
    debut = aDebut;
  }

  public Date getFin() {
    return fin;
  }

  public void setFin(Date aFin) {
    fin = aFin;
  }

  public String getTitre() {
    return titre;
  }

  public void setTitre(String aTitre) {
    titre = aTitre;
  }

  public String getType() {
    return type;
  }

  public void setType(String aType) {
    type = aType;
  }

  public List<SelectItem> getTypes() {
    List<SelectItem> types = new ArrayList<SelectItem>();
    types.add(new SelectItem("date", "Par Dates"));
    types.add(new SelectItem("titre", "Par Titre"));
    return types;
  }

  public boolean getDoSearchByDate() {
    return type.equals("date");
  }

  public boolean getDoSearchByTitle() {
    return !getDoSearchByDate();
  }

  /**
   * @return the article
   */
  public Article getArticle() {
    return article;
  }

  /**
   * @param article the article to set
   */
  public void setArticle(Article article) {
    this.article = article;
  }

  public Image getImage() {
    return image;
  }

  public HtmlOutputText getText() {
    return text;
  }

  public void setText(HtmlOutputText text) {
    this.text = text;
  }

  /**
   * @return the articles
   */
  public List<Article> getArticlesRecents() {
    try {
      return articleDao.lesArticlesRecents();
    } catch (Exception e) {
      return null;
    }
  }

  public List<Article> getArticles() {
    return articleDao.tousLesArticles();
  }

  public String back() {
    return retour;
  }

  public void listener(FileUploadEvent event) throws Exception {
    UploadedFile file = event.getUploadedFile();
    image = new Image();
    image.setNom(strDate() + file.getName());
    image.setImage(file.getData());
    image.setDescription("No description");
  }

  public void attrListener(ActionEvent event) {
    article = new Article();
    String title = (String) event.getComponent().getAttributes().get("titre");
    retour = (String) event.getComponent().getAttributes().get("retour");
    article = articleDao.trouverArticle(title);
  }

  public String retrieveArticleForDetails() {
    image = new Image();
    ImageArticle ia = new ImageArticleDaoImpl().trouverImageArticle(article);
    if (ia != null) {
      image = ia.getImage();
    }
    return "/pages/details/article.xhtml?faces-redirect=true";
  }

  public String supprimer() {
    if (!DAOFactory.getArticleMembreDao().supprimerArticleMembre(article) || !articleDao.supprimerArticle(article)) {
      FacesContext.getCurrentInstance().addMessage(null,
          new FacesMessage(FacesMessage.SEVERITY_ERROR, "Un erreur est survenu. Echec de l'opération!", ""));
      return "";
    }
    article = new Article();
    return "/pages/actualites.xhtml?faces-redirect=true";
  }

  private String strDate() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmm");
    return sdf.format(new Date()) + "_";
  }
}
